import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";
import UserList from "../views/sys/user/Index.vue";
import Login from "../views/common/Login.vue";
import { getUser } from "../utils/session";
import DeptList from "../views/sys/dept/index.vue";
import Customer from "../views/customer/index.vue"
import Contract from "../views/contract/Index.vue";
import Product from "../views/product/Index.vue"


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/home",
      name: "home",
      component: Home,
      children: [
        {
          path: "/user",
          name: "user",
          component: UserList,
        },
        {
          path:"/dept",
          name:"dept",
          component:DeptList,
        },{
          path:"/customer",
          name:"customer",
          component:Customer,
        },{
          path:"/contract/:type",
          name:"contract",
          component:Contract,
        },{
            path:"/product",
            name:"product",
            component:Product,
        }
      ],
    },
    {
      path:"/",
      name:"login",
      component: Login
    }
  ],
});

//前置守卫
router.beforeEach((to,from,next)=>{
  //判断当前访问的是否是登录界面
  if(to.path == "/"){
    //说明是登录界面，直接放行
    next();
  }else{
    //不是登录界面
    //判断用户是否登录
    let user = getUser();
    if(user){
      //用户存在 直接放行
      next();
    }else{
      //用户不存在 跳转到登录界面
      next("/")
    }
  }
})

export default router;